<template>
  <div>
    <upload-excel :on-success="handleSuccess" />
  </div>
</template>
<script>
import UploadExcel from '@/components/UploadExcel'
// 处理时间格式
import { formatExcelDate } from '@/utils/tree'
// 导入api
import { importEmployee } from '@/api/employees'
export default {
  name: 'Import',
  components: {
    UploadExcel
  },
  data() {
    return {

    }
  },
  computed: {
  },
  created() {
  },
  methods: {
    handleSuccess({ header, results }) {
      //   按接口要求 组装数据
      const data = this.transExcel(results)
      this.doImport(data)
    },
    // excel表中英文转换
    transExcel(results) {
      const mapInfo = {
        '入职日期': 'timeOfEntry',
        '手机号': 'mobile',
        '姓名': 'username',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName',
        '聘用形式': 'formOfEmployment'
      }
      return results.map(zhObj => {
        const enObj = {}
        const zhKeys = Object.keys(zhObj)

        zhKeys.forEach(zhKey => {
          const enKey = mapInfo[zhKey]
          if (enKey === 'timeOfEntry' || enKey === 'timeOfEntry') {
            // 后端需要的日期格式是标准时间
            enObj[enKey] = new Date(formatExcelDate(zhObj[zhKey]))
          } else {
            enObj[enKey] = zhObj[zhKey]
          }
        })
        return enObj
      })
    },
    // 发送请求导入文件
    async doImport(data) {
      try {
        await importEmployee(data)
        this.$message.success('导入成功！')
        // 页面后退
        this.$router.back()
      } catch (err) {
        console.log(err)
        this.$message.error('导入成功！')
      }
    }
  }
}
</script>
<style lang='less'  scoped>

</style>
